const request = require('sync-request');

class Request {

    static post(url, data, headers) {
        let options = {
            headers,
            body: typeof data === "string" ? data : JSON.stringify(data)
        };
        let response = request("POST", url, options);
        return new Response(response);
    }

    static put(url, data, headers) {
        let options = {
            headers,
            body: typeof data === "string" ? data : JSON.stringify(data)
        };
        let response = request("PUT", url, options);
        return new Response(response);
    }

    static get(url, params, headers) {
        if (params) {
            url += `?${Request._jsonToXWwwFormUrlencoded(params)}`;
            url = encodeURI(url);
        }
        let options = {
            headers
        };
        let response = request("GET", url, options);
        return new Response(response);
    }

    static _jsonToXWwwFormUrlencoded(json) {
        let xWwwFormUrlencoded = "";
        let names = Object.keys(json).sort((key1, key2) => key1 > key2 ? 1 : -1);
        names.forEach((name, index) => {
            xWwwFormUrlencoded += `${name}=${json[name]}`
            if (index !== names.length - 1) {
                xWwwFormUrlencoded += "&";
            }
        });
        return xWwwFormUrlencoded;
    }

}

class Response {
    constructor(response) {
        this.statusCode = response.statusCode;
        this.headers = response.headers;
        this.text = response.body.toString("utf-8");
    }
}

module.exports = Request;